﻿
using System;
using System.Configuration;
using Best.SmartCms.Core.Utility;
using Microsoft.Extensions.Configuration;

namespace Best.SmartCms.Utility
{
    public class AESHandler
    {
        private static readonly string key = ConfigurationManager.AppSettings["AES_KEY"];

        /// <summary>
        /// 加密，如果param为空，返回null并在日志中记录Warn
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string Encrypt(string param)
        {
            return Encrypt(param, key);
        }

        /// <summary>
        /// 接受外部加密的Key进行加密，如果param为空，返回null并在日志中记录Warn
        /// </summary>
        /// <param name="param"></param>
        /// <param name="desKey"></param>
        /// <returns></returns>
        public static string Encrypt(string param, string desKey)
        {
            try
            {
                if (string.IsNullOrEmpty(param))
                {
                    throw new ArgumentNullException(param, "Encrypt param can not be null");
                }

                return AesUtility.Encrypt(param, desKey);
            }
            catch (System.Exception ex)
            {

                NLogManager.LogWarn(ex);
                NLogManager.LogTrace("Encrypt param is " + param);
                return null;
            }
        }
        /// <summary>
        /// 解密，如果param为空，返回null并在日志中记录Warn
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string Decrypt(string param)
        {
            return Decrypt(param, key);
        }

        /// <summary>
        /// 接受外部加密的Key解密进行加密，如果param为空，返回null并在日志中记录Warn
        /// </summary>
        /// <param name="param"></param>
        /// <param name="desKey"></param>
        /// <returns></returns>
        public static string Decrypt(string param, string desKey)
        {
            try
            {
                if (string.IsNullOrEmpty(param))
                {
                    throw new ArgumentNullException(param, "Decrypt param can not be null");
                }

                return AesUtility.Decrypt(param, desKey);
            }
            catch (System.Exception ex)
            {
                NLogManager.LogWarn(ex);
                NLogManager.LogTrace("Decrypt param is " + param);
                return null;
            }
        }
    }
}
